﻿@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>任务列表</title>
    <style>
        [v-cloak] {
            display: none;
        }

        .classFinished label {
            color: #ddd;
            text-decoration: line-through;
        }

        #app {
            width: 600px;
            border: 1px solid #ddd;
            margin: 30px auto;
            padding: 20px;
        }

        .inputModel {
            width: 576px;
            height: 45px;
            line-height: 45px;
            padding-left: 20px;
            font-size: 16px;
            border-radius: 5px;
            outline: none;
            -webkit-appearance: none;
            border: 2px solid #aaa;
        }

        .list {
            padding: 0;
            margin: 30px 0 0;
            border: 1px solid #ddd;
        }

            .list li {
                list-style: none;
                border-bottom: 1px solid #ddd;
                padding: 0 70px 0 50px;
                position: relative;
            }

                .list li label {
                    font-size: 22px;
                    display: block;
                    padding: 15px 0px;
                    line-height: 1.5;
                }

        .btnDel {
            position: absolute;
            right: 10px;
            top: 20px;
            border: 1px solid #eee;
            border-radius: 3px;
            padding: 5px 10px;
            font-size: 12px;
            display: none;
        }

        .list li:hover .btnDel {
            display: block;
        }

        .toggle {
            position: absolute;
            left: 15px;
            top: 25px;
        }

        .edit input[type=text] {
            width: 100%;
            border: 1px solid #999;
            box-sizing: border-box;
            padding: 15px 10px;
            font-size: 22px;
        }

        .edit {
            display: none;
        }

        .classEdit .view {
            display: none;
        }

        .classEdit .edit {
            display: block;
        }
    </style>
</head>
<body>
    <div id="app" v-cloak>
        <input type="text" v-model="newItem" placeholder="需要完成什么" class="inputModel" v-on:keyup.enter="addNew">
        <ul>
            <li>
                <label><input type="radio" value="all" v-model="visibility" />所有（{{allCount}}）</label>
            </li>
            <li>
                <label><input type="radio" value="active" v-model="visibility" />未完成（{{activeCount}}）</label>
            </li>
            <li>
                <label><input type="radio" value="completed" v-model="visibility" />已完成（{{completedCount}}）</label>
            </li>
        </ul>
        <button v-show="completedCount" v-on:click="delCompletedItem">删除已完成的任务</button>
        <ul class="list">
            <li v-for="item in filteredTodos" v-bind:class="{ 'classFinished': item.finished,'classEdit':item==editedTodo }">
                <div class="view">
                    <input type="checkbox" class="toggle" v-model="item.finished" />
                    <label v-on:dblclick="editTodo(item)">
                        {{item.label}}
                    </label>
                    <span class="btnDel" v-on:click="delItem(item)">
                        删除
                    </span>
                </div>
                <div class="edit">
                    <input type="text" v-model="item.label" v-on:blur="editItem(item)" v-on:keyup.enter="editItem(item)" v-on:keyup.esc="cancelEdit(item)">
                </div>
            </li>
        </ul>
        <div>
           {{todolist|json}}
        </div>
    </div>
    <script src="@Url.Content("~/Scripts/vue.js")"></script>
    <script src="@Url.Content("~/Scripts/vue-resource.min.js")"></script>

    <script>

        var filters = {
            all: function (todos) {
                return todos;
            },
            active: function (todos) {
                return todos.filter(function (todo) {
                    return !todo.finished;
                });
            },
            completed: function (todos) {
                return todos.filter(function (todo) {
                    return todo.finished;
                });
            }
        };
        var MyComponent = Vue.extend({
            template: '<div>A custom component!</div>'
        })
        // 注册
        Vue.component('my-component', MyComponent)

        var isInit = false;
        var vm = new Vue({
            el: '#app',
            data: {
                todolist: [],
                newItem: '',
                editedTodo: null,
                visibility: 'all'
            },
            init: function () {
                console.log('init ');
                getTodolistFromDatabase();
            },
            computed: {
                filteredTodos: function () {
                    return filters[this.visibility](this.todolist);
                },
                allCount: function () {
                    return this.todolist.length;
                },
                activeCount: function () {
                    return filters.active(this.todolist).length;
                },
                completedCount: function () {
                    return filters.completed(this.todolist).length;
                }
            },
            methods: {
                changeState: function (param) {
                    param.finished = !param.finished;
                },
                addNew: function () {
                    var newOne = {
                        label: this.newItem,
                        finished: false
                    }
                    this.todolist.unshift(newOne);
                    this.newItem = '';
                },
                editTodo: function (param) {
                    this.beforeEditCache = param.label;
                    this.editedTodo = param;
                },
                editItem: function (param) {
                    if (!this.editedTodo)
                        return;
                    if (!param.label) {
                        this.todolist.$remove(param);
                    }
                    this.editedTodo = null;
                },
                cancelEdit: function (param) {
                    param.label = this.beforeEditCache;
                    this.editedTodo = null;
                },
                delItem: function (param) {
                    if (confirm("确认删除吗？")) {
                        this.todolist.$remove(param);
                    }
                },
                delCompletedItem: function () {
                    if (confirm("确认删除所有已完成任务吗？")) {
                        this.todolist = filters.active(this.todolist);
                    }
                }
            },
            watch: {
                'todolist': {
                    deep: true,
                    handler: function (val, oldVal) {
                        var temp = JSON.stringify(val);
                        console.log('watch oldVal=' + oldVal);
                        window.localStorage.setItem('todolist', temp);


                        this.$http.post("@Url.Action("Save")", { body: "" }, { params: { uid: "1", todolist: temp } }).then(function (response) {
                                console.log("watch:POST:success===>" + response.body);
                            }, function (response) {
                            });

                    }
                }
            },           
            ready: function () {
                console.log('ready');
            }
        })

        function getTodolist() {
            //【BUG】由于是异步的，会先返回空的temp，后面才从数据库里返回值
            return JSON.parse(window.localStorage.getItem('todolist')) || [];
        }

        function getTodolistFromDatabase() {
            Vue.http.post("@Url.Action("GetlistByUid")", { body: "" }, { params: { uid: "1" } }).then(function (response) {
                // success callback
                console.log("getTodolistFromDatabasesuccess===>" + response.body.state);
                if (response.body.state == "success") {
                    //set会触发watch
                    vm.$set('todolist', JSON.parse(response.body.todolist));
                }
                else
                {
                    vm.$set('todolist', getTodolist());
                }
            }, function (response) {
                console.log("error===>" + JSON.stringify(response));
            });
        }

    </script>

</body>
</html>
